import React, { useState, useEffect, useRef } from 'react';
import { Text, View, StyleSheet, Pressable, FlatList, Image } from 'react-native';
import { createStackNavigator } from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/FontAwesome';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 测试数据
const postData = [
    { id: '1', title: '第一条帖子消息' },
    { id: '2', title: '第二条帖子消息' },
    // 更多测试数据...
];

function HomeScreen({ navigation }) {
    const [hasMessages, setHasMessages] = useState(true); // 假设状态变量控制消息显示
    const [userInfo, setUserInfo] = useState({});
    const [markedList, setMarkedList] = useState([]);
    const [mark, setMarked] = useState([]);
    const [view, setView] = useState([]);
    const [refreshing, isRefresh] = useState(true);
    const getMarkedList = async () => {
        axios.get('http://47.111.227.58:3000/dynamic/getUserMarkedDynamics', {
            params: {
                username: userInfo.username,
            },
        })
            .then((res) => {
                // console.log(res.data);
                setMarkedList(res.data.results)
                const initialMarked = res.data.results.map(item => item.markUsers?.split(',').includes(userInfo.username));
                setMarked(initialMarked);
                const initialView = res.data.results.map(item => item.view);
                setView(initialView)
                isRefresh(false);
            })
            .catch((error) => {
                console.error(error);
            });
    };
    const handleRefresh = () => {
        isRefresh(true);
        getMarkedList();
    }
    const handlePostClick = (postId, index) => {
        navigation.navigate('PostDetail', { postId: postId });
        let newView = [...view];
        newView[index] = Number(newView[index]) + 1;
        setView(newView);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicView', {
            data: {
                id: markedList[index].id,
                view: newView[index]
            }
        }).then(res => {
            console.log(res.data);
        });
    };
    const handleMarked = (index) => {
        if (mark[index]) {
            let newMarked = [...mark];
            newMarked[index] = false;
            setMarked(newMarked);
            axios.post('http://47.111.227.58:3000/dynamic/updateMarkUsers', {
                postId: markedList[index].id,
                userId: userInfo.username
            }).then(res => {
                console.log(res.data);
                getMarkedList()
            });
        } else {
            let newMarked = [...mark];
            newMarked[index] = true;
            setMarked(newMarked);
            axios.post('http://47.111.227.58:3000/dynamic/updateMarkUsers', {
                postId: markedList[index].id,
                userId: userInfo.username
            }).then(res => {
                console.log(res.data);
                getMarkedList()
            });
        }
    };
    useEffect(() => {
        (async () => {
            //   isRefresh(true);
            // getDynamicList()
            const userinfo = await AsyncStorage.getItem('userInfo');
            if (userinfo) {
                setUserInfo(JSON.parse(userinfo))
            }
        })();
    }, []);
    useEffect(() => {
        (async () => {
            if (userInfo.username) {
                console.log(userInfo.username)
                await getMarkedList();
            }
        })();
    }, [userInfo]);
    const renderItem = ({ item, index }) => (
        <Pressable onPress={() => handlePostClick(item.id, index)}>
            <View style={styles.postContain}>
                <View style={styles.postItem}>
                    {item.imgUrl && (
                        <Image style={styles.postImage} source={{ uri: item.imgUrl }} />
                    )}
                    <Text style={styles.postItemText}>{item.desc}</Text>
                </View>
                <View style={styles.postItemBottom}>
                    <Pressable style={styles.interactionButton} onPress={() => handleMarked(index)}>
                        <Icon name="low-vision" size={20} color="#576BA2" />
                        <Text style={styles.postItemBottomIconText}>取消追踪</Text>
                    </Pressable>
                    <Text style={styles.postItemBottomText}>{item.uploadTime}</Text>
                </View>
            </View>
        </Pressable>
    );

    return (
        <View style={styles.container}>
            {/* 头部图标 */}
            <View style={styles.headerContainer}>
                <View>
                    <Pressable
                        style={[styles.headerIcon, { backgroundColor: '#3498db' }]}
                        onPress={() => navigation.navigate('Comments')}>
                        <Icon name="comment" size={20} color="#fff" />
                    </Pressable>
                    <Text style={styles.iconText}>评论</Text>
                </View>
                <View>
                    <Pressable
                        style={[styles.headerIcon, { backgroundColor: '#e67e22' }]}
                        onPress={() => navigation.navigate('Likes')}>
                        <Icon name="thumbs-up" size={20} color="#fff" />
                    </Pressable>
                    <Text style={styles.iconText}>赞/赞赏</Text>
                </View>
                <View>
                    <Pressable
                        style={[styles.headerIcon, { backgroundColor: '#f1c40f' }]}
                        onPress={() => navigation.navigate('Events')}>
                        <Icon name="calendar" size={20} color="#fff" />
                    </Pressable>
                    <Text style={styles.iconText}>攒局</Text>
                </View>
                <View>
                    <Pressable
                        style={[styles.headerIcon, { backgroundColor: '#2ecc71' }]}
                        onPress={() => navigation.navigate('Messages')}>
                        <Icon name="envelope" size={20} color="#fff" />
                    </Pressable>
                    <Text style={styles.iconText}>私聊</Text>
                </View>
            </View>
            <View style={styles.blank}></View>
            {/* 主内容区 */}
            <View style={styles.mainContent}>
                <View style={styles.mainContentTitleContainer}>
                    <Text style={styles.mainContentTitle}>帖子动态</Text>
                </View>
                <View style={styles.blank}></View>
                {/* 帖子动态栏目 */}
                <FlatList
                    data={hasMessages ? markedList : []}
                    renderItem={renderItem}
                    keyExtractor={item => item.id}
                    ListEmptyComponent={<Text style={styles.emptyMessage}>暂无消息</Text>}
                    refreshing={refreshing}
                    onRefresh={handleRefresh}
                />
            </View>
        </View>
    );
}

// 添加更多页面组件
function CommentsScreen({ route, navigation }) {
    // 页面内容
}

function LikesScreen({ route, navigation }) {
    // 页面内容
}

function EventsScreen({ route, navigation }) {
    // 页面内容
}

function MessagesScreen({ route, navigation }) {
    // 页面内容
}

// 创建StackNavigator
const Stack = createStackNavigator();

export default function App() {
    return (
        <Stack.Navigator>
            <Stack.Screen name="Home" component={HomeScreen} options={{
                title: '消息', headerTitleAlign: 'center',
                headerStyle: {
                    backgroundColor: '#EB7A76',
                },
                headerTintColor: '#fff',
            }} />
            <Stack.Screen name="Comments" component={CommentsScreen} options={{
                title: '回复我的', headerTitleAlign: 'center',
                headerStyle: {
                    backgroundColor: '#EB7A76',
                },
                headerTintColor: '#fff',
            }} />
            <Stack.Screen name="Likes" component={LikesScreen} options={{
                title: '赞/赞赏', headerTitleAlign: 'center',
                headerStyle: {
                    backgroundColor: '#EB7A76',
                },
                headerTintColor: '#fff',
            }} />
            <Stack.Screen name="Events" component={EventsScreen} options={{
                title: '攒局消息', headerTitleAlign: 'center',
                headerStyle: {
                    backgroundColor: '#EB7A76',
                },
                headerTintColor: '#fff',
            }} />
            <Stack.Screen name="Messages" component={MessagesScreen} options={{
                title: '私聊', headerTitleAlign: 'center',
                headerStyle: {
                    backgroundColor: '#EB7A76',
                },
                headerTintColor: '#fff',
            }} />
        </Stack.Navigator>
    );
}

// 定义样式
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    headerContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',
        paddingVertical: 10,
    },
    headerIcon: {
        width: 50,
        height: 50,
        borderRadius: 25,
        justifyContent: 'center',
        alignItems: 'center',
    },
    iconText: {
        textAlign: 'center',
        color: '#333',
        marginTop: 5,
    },
    mainContent: {
        flex: 1,
        backgroundColor: '#F4F4F4',
    },
    mainContentTitleContainer: {
        backgroundColor: '#fff',
        width: '100%',
        height: 40,
        justifyContent: 'center',
    },
    mainContentTitle: {
        marginLeft: 10,
        fontSize: 14,
        fontWeight: 'bold',
    },
    interactionButton: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingRight: 15,
    },
    postItem: {
        backgroundColor: '#F7F7F7',
        margin: 20,
        height: 60,
        // borderBottomWidth: 1,
        // borderBottomColor: '#e0e0e0',
        flexDirection: 'row',
        display: 'flex',
        alignItems: 'center'
    },
    postItemBottom: {
        backgroundColor: '#fff',
        // padding: 20,
        borderBottomWidth: 1,
        borderBottomColor: '#e0e0e0',
        flexDirection: 'row',
        display: 'flex',
        justifyContent: 'flex-start',
        paddingLeft: 20,
        paddingRight: 20,
        paddingBottom: 10,
    },
    postItemBottomText: {
        display: 'flex',
        marginLeft: 'auto',
        marginRight: 0,
        color: '#777777'
    },
    postItemBottomIconText: {
        display: 'flex',
        paddingLeft: 5,
        fontWeight: 'bold',
        color: '#576BA2',
    },
    postContain: {
        // flexDirection: 'column',
        backgroundColor: '#fff'
    },
    postItemText: {
        fontSize: 16,
        paddingLeft: 5,
    },
    emptyMessage: {
        textAlign: 'center',
        marginTop: 20,
        fontSize: 16,
    },
    postStatus: {
        marginVertical: 20,
        marginLeft: 10,
    },
    blank: {
        height: 5,
        backgroundColor: '#F4F4F4',
    },
    postImage: {
        width: 60,
        height: 60,
        borderRadius: 4,
        // marginLeft: 10,
    },
});